package com.wsz.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsz.security.pojo.Role;
import com.wsz.security.pojo.User;
import com.wsz.security.pojo.UserRole;
import com.wsz.security.service.RoleService;
import com.wsz.security.service.UserRoleService;
import com.wsz.security.service.UserService;
import com.wsz.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* author wangs
* description 针对表【user】的数据库操作Service实现
* createDate 2022-11-24 15:01:20
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{


    private final RoleService roleService;

    private final UserRoleService userRoleService;

    @Autowired
    public UserServiceImpl(RoleService roleService, UserRoleService userRoleService) {
        this.roleService = roleService;
        this.userRoleService = userRoleService;
    }

    @Override
    public User getUserByUserName(String username) {
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().eq("username", username));

        List<String> roleNames = new ArrayList<>();
        userRoles.forEach(userRole -> roleNames.add(userRole.getRolename()));

        user.setRoles(roleService.list(new QueryWrapper<Role>().in("name",roleNames)));

        return user;
    }

    @Override
    public void addRoleToUser(String username, String roleName) {
        userRoleService.save(new UserRole(null,username,roleName));
    }

    @Override
    public List<User> getUserList() {
        List<User> users = baseMapper.selectList(null);

        List<Role> roles = roleService.list();

        List<UserRole> userRoles = userRoleService.list();

        userRoles.forEach(userRole -> {

            for (User user : users) {
                if (user.getUsername().equals(userRole.getUsername())) {
                    for (Role role : roles) {
                        System.out.println(role.getName() + "   " + userRole.getRolename());
                        if (role.getName().equals(userRole.getRolename())) {
                            user.getRoles().add(role);
                        }

                    }
                }
            }

        });

        System.out.println(users);
        return users;
    }
}




